package com.example.minio.controller;

import io.minio.MinioClient;
import io.minio.ObjectWriteArgs;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
public class MinioUploadController {

    /**通过此对象完成文件的上传*/
    @Autowired
    private MinioClient minioClient;

    @PostMapping("/api/minio/upload")
    public String doUpload(@RequestPart("picFile") MultipartFile picFile)
            throws Exception{
        //1.为文件重命名
        String originalFilename=picFile.getOriginalFilename();
        String newFileName= UUID.randomUUID()+
                originalFilename.substring(originalFilename.lastIndexOf("."));
        //2.上传文件
        minioClient.putObject(
                PutObjectArgs.builder()
                            .bucket("public")
                            .object(newFileName)
                            .contentType(picFile.getContentType())
                            .stream(picFile.getInputStream(),picFile.getSize(), ObjectWriteArgs.MIN_MULTIPART_SIZE).build());

        return "/public/"+newFileName;
    }
}
